package com.yiyahui.common.utils;

import com.yiyahui.framework.config.properties.AliSTSPropertis;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * aliSTS工具类
 * 
 * @author mike
 */
public class STSUtils {

    private static final Logger logger = LoggerFactory.getLogger(STSUtils.class);

    // sts属性
    private static AliSTSPropertis stsPropertis;

    public AliSTSPropertis getSTSPropertis() {
        return this.stsPropertis;
    }

    public void setSTSPropertis(AliSTSPropertis stsPropertis) {
        this.stsPropertis = stsPropertis;
    }

    // 获取oss相关token，使用oss的arnrole
    public static AssumeRoleResponse.Credentials getOSSCredentials(Long duration) {
        AssumeRoleResponse.Credentials credentials = null;
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", stsPropertis.getEndPoint());
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", stsPropertis.getAccessKeyId(),
                    stsPropertis.getAccessKeySecret());
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(stsPropertis.getOSSRoleArn());
            request.setRoleSessionName(stsPropertis.getRoleSessionName());
            request.setDurationSeconds(duration == null ? 900L : duration);
            request.setProtocol(ProtocolType.HTTPS); // 必须使用HTTPS协议访问STS服务);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            credentials = response.getCredentials();
            logger.info("Expiration: " + credentials.getExpiration());
            logger.info("Access Key Id: " + credentials.getAccessKeyId());
            logger.info("Access Key Secret: " + credentials.getAccessKeySecret());
            logger.info("Security Token: " + credentials.getSecurityToken());
            logger.info("RequestId: " + response.getRequestId());
        } catch (ClientException e) {
            logger.info("Failed：");
            logger.info("Error code: " + e.getErrCode());
            logger.info("Error message: " + e.getErrMsg());
            logger.info("RequestId: " + e.getRequestId());
        }
        return credentials;
    }

}
